package com.zhu.rpc.server;

import com.zhu.rpc.RpcProtocol;
import com.zhu.rpc.client.RemoteConsumer;
import com.zhu.rpc.RpcMethod;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Component
public class ProviderAnnotationScanner implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        RemoteProvider remoteProvider = bean.getClass().getAnnotation(RemoteProvider.class);
        if (remoteProvider != null){
            String className = remoteProvider.name();
            if ("".equals(className)){
                className = beanName;
            }
            RpcMethod.providerClassAlias.put(className,beanName);
            for (Method method : bean.getClass().getDeclaredMethods()){
                if (method.getAnnotation(UnExposeMethod.class) == null){
                    StringBuilder name = new StringBuilder(className).append(",").append(method.getName());
                    for (Class t:method.getParameterTypes()){
                        if (RpcProtocol.isNolmalType(t)){
                            name.append(",").append(t.getName());
                        }else {
                            name.append(",").append(t.getSimpleName());
                        }
                    }
                    RpcMethod.providerMethodMap.put(name.toString(),method);
                }
            }
        }

        RemoteConsumer remoteConsumer = bean.getClass().getAnnotation(RemoteConsumer.class);
        if (remoteConsumer != null){
            String className = remoteConsumer.name();
            if ("".equals(className)){
                className = beanName;
            }
            for (Method method : bean.getClass().getDeclaredMethods()){
                if (method.getAnnotation(UnExposeMethod.class) == null){
                    StringBuilder name = new StringBuilder(className).append(",").append(method.getName());
                    for (Class t:method.getParameterTypes()){
                        name.append(",").append(t.getName());
                    }
                    RpcMethod.consumerMethodMap.put(name.toString(),method);
                }
            }
        }
        return bean;
    }
}
